/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Formulario_cliente.java
 *
 * Created on 11/06/2011, 13:27:55
 */

package formularios;

import formularios.model.Clientes;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.text.MaskFormatter;

/**
 *
 * @author Ramon
 */
public class Formulario_cliente extends javax.swing.JInternalFrame {

    /** Creates new form Formulario_cliente */
    public Formulario_cliente() {
        
        initComponents();
        //quando apertar enter, o botão salvar será acionado
        getRootPane().setDefaultButton(btn_cli_salvar);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        radGroup_cli_sexo = new javax.swing.ButtonGroup();
        try {
            MaskFormatter formato_cpf = new MaskFormatter("###.###.###-##");
            txt_cli_cpf = new JFormattedTextField(formato_cpf);
            txt_cli_nome = new javax.swing.JTextField();
            MaskFormatter formato_dtns = new MaskFormatter("##/##/####");
            txt_cli_dtns = new JFormattedTextField(formato_dtns);
            txt_cli_end = new javax.swing.JTextField();
            txt_cli_email = new javax.swing.JTextField();
            lab_cli_cpf = new javax.swing.JLabel();
            lab_cli_nome = new javax.swing.JLabel();
            lab_cli_tel = new javax.swing.JLabel();
            lab_cli_end = new javax.swing.JLabel();
            lab_cli_dtns = new javax.swing.JLabel();
            lab_cli_email = new javax.swing.JLabel();
            lab_cli_renda_individual = new javax.swing.JLabel();
            lab_cli_renda_familiar = new javax.swing.JLabel();
            MaskFormatter formato_telefone = new MaskFormatter("(##)####-####");
            txt_cli_tel = new JFormattedTextField(formato_telefone);
            lab_cli_sexo = new javax.swing.JLabel();
            txt_cli_renda_individual = new formularios.MoedaTextField();
            txt_cli_renda_familiar = new formularios.MoedaTextField();
            btn_cli_salvar = new javax.swing.JButton();
            btn_cli_limpar = new javax.swing.JButton();
            rad_cli_masc = new javax.swing.JRadioButton();
            rad_cli_fem = new javax.swing.JRadioButton();
            btn_cli_excluir = new javax.swing.JToggleButton();

            setClosable(true);
            setIconifiable(true);
            setMaximizable(true);
            setResizable(true);
            setTitle("Formulário de Cliente");

        } catch (ParseException ex) {
            Logger.getLogger(Formulario_cliente.class.getName()).log(Level.SEVERE, null, ex);
        }
        txt_cli_cpf.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txt_cli_cpfActionPerformed(evt);
            }
        });
        txt_cli_cpf.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txt_cli_cpfFocusLost(evt);
            }
        });

        lab_cli_cpf.setText("CPF");

        lab_cli_nome.setText("Nome Completo");

        lab_cli_tel.setText("Telefone");

        lab_cli_end.setText("Endereço");

        lab_cli_dtns.setText("Data de Nascimento");

        lab_cli_email.setText("E-mail");

        lab_cli_renda_individual.setText("Renda Individual");

        lab_cli_renda_familiar.setText("Renda Mensal Familiar");

        lab_cli_sexo.setText("Sexo");

        btn_cli_salvar.setText("Salvar");
        btn_cli_salvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_cli_salvarActionPerformed(evt);
            }
        });

        btn_cli_limpar.setText("Limpar");
        btn_cli_limpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_cli_limparActionPerformed(evt);
            }
        });

        radGroup_cli_sexo.add(rad_cli_masc);
        rad_cli_masc.setText("Masculino");

        radGroup_cli_sexo.add(rad_cli_fem);
        rad_cli_fem.setText("Feminino");
        rad_cli_fem.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        btn_cli_excluir.setText("Excluir");
        btn_cli_excluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_cli_excluirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lab_cli_dtns)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txt_cli_dtns, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lab_cli_cpf)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txt_cli_cpf, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lab_cli_nome)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txt_cli_nome, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lab_cli_tel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txt_cli_tel, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lab_cli_end)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txt_cli_end, javax.swing.GroupLayout.PREFERRED_SIZE, 218, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(73, 73, 73)
                                        .addComponent(btn_cli_excluir))
                                    .addComponent(btn_cli_salvar))
                                .addGap(18, 18, 18)
                                .addComponent(btn_cli_limpar))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lab_cli_renda_familiar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txt_cli_renda_familiar, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                    .addComponent(lab_cli_renda_individual)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(txt_cli_renda_individual))
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                    .addComponent(lab_cli_email)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(txt_cli_email, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lab_cli_sexo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(rad_cli_fem)
                            .addComponent(rad_cli_masc))))
                .addContainerGap(39, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lab_cli_cpf)
                            .addComponent(txt_cli_cpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lab_cli_nome)
                            .addComponent(txt_cli_nome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lab_cli_dtns)
                            .addComponent(txt_cli_dtns, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lab_cli_tel)
                            .addComponent(txt_cli_tel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lab_cli_sexo)
                            .addComponent(rad_cli_masc)))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lab_cli_end)
                            .addComponent(txt_cli_end, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lab_cli_email)
                            .addComponent(txt_cli_email, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(lab_cli_renda_individual)
                            .addComponent(txt_cli_renda_individual, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lab_cli_renda_familiar)
                            .addComponent(txt_cli_renda_familiar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(btn_cli_salvar)
                        .addComponent(btn_cli_excluir)
                        .addComponent(btn_cli_limpar))
                    .addComponent(rad_cli_fem))
                .addContainerGap(53, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btn_cli_salvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_cli_salvarActionPerformed

        char sexo = 0;
        String str_individual = "";
        String str_familiar = "";

        //cria uma instancia relacionada ao contexto de persistencia
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("BancoImobiliaria");
        EntityManager em = emf.createEntityManager();
        //cria uma instancia para controlar a transação
        EntityTransaction trans = em.getTransaction();

        //vefirica qual sexo está selecionado
        if(rad_cli_masc.isSelected())
            sexo = 'M';
        else if(rad_cli_fem.isSelected())
            sexo = 'F';

        //muda a str_individual para ser possível transformá-la em double
        str_individual = txt_cli_renda_individual.getText();
        str_individual = str_individual.replace(".", "");
        str_individual = str_individual.replaceAll(",", ".");

        //muda a str_familiar para ser possível transformá-la em double
        str_familiar = txt_cli_renda_familiar.getText();
        str_familiar = str_familiar.replace(".", "");
        str_familiar = str_familiar.replaceAll(",", ".");

		//formato para data
        DateFormat formato_dtns = new SimpleDateFormat("dd/MM/yyyy");

        //verifica se a data é real
        formato_dtns.setLenient(false);

        //transforma a String dtns em Date
        Date dtns = null;

        try {
            dtns = formato_dtns.parse(txt_cli_dtns.getText());
        } catch (ParseException ex) {
            //Logger.getLogger(Formulario_cliente.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(this, "Data de nascimento inválida.");
            return;
        }

        //instancia da classe Clinetes
        Clientes cli = new Clientes(txt_cli_cpf.getText(), txt_cli_nome.getText(), dtns, sexo,
                                    txt_cli_tel.getText(), txt_cli_end.getText(), txt_cli_email.getText(),
                                    Double.parseDouble(str_individual),
                                    Double.parseDouble(str_familiar));

       try {
            //insere ou atualiza um cliente
            trans.begin();
            em.merge(cli);
            trans.commit();
            JOptionPane.showMessageDialog(this, "Cliente cadastrado com sucesso.");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Erro ao inserir. Por favor, confira os dados.");
        }

        //encerra a transação
        em.close();
        emf.close();
    }//GEN-LAST:event_btn_cli_salvarActionPerformed

    private void btn_cli_excluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_cli_excluirActionPerformed

        //verifica se existe algum cpf digitado
        if(txt_cli_cpf.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Entre com o CPF do cliente para excluí-lo.");
            txt_cli_cpf.requestFocus();
        }else
        {
            //cria gerenciador do BancoImobiliaria
            EntityManagerFactory emf = Persistence.createEntityManagerFactory("BancoImobiliaria");
            EntityManager em = emf.createEntityManager();

            //procura o cliente com o CPF digitado
            Clientes cli = em.find(Clientes.class, txt_cli_cpf.getText());

            //verifica se o cliente existe
            if(cli == null) {
                JOptionPane.showMessageDialog(this, "CPF do cliente não encontrado. Entre com o CPF correto.");
                txt_cli_cpf.requestFocus();
            }else
            {
                //mensagem de alerda da exclusão do cliente
                if (JOptionPane.showConfirmDialog(this,
                        "Esta operação não poderá ser desfeita.\n Deseja continuar?",
                        "Aviso",
                        JOptionPane.YES_NO_OPTION,
                        JOptionPane.WARNING_MESSAGE) == JOptionPane.NO_OPTION)
                    return;

                //obtem uma transação
                EntityTransaction trans = em.getTransaction();

                //remove cliente
                trans.begin();
                em.remove(cli);
                trans.commit();
                
                //encerra a transação
                em.close();
                emf.close();

                limparCampos();
            }
        }
    }//GEN-LAST:event_btn_cli_excluirActionPerformed

    private void btn_cli_limparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_cli_limparActionPerformed

        limparCampos();
    }//GEN-LAST:event_btn_cli_limparActionPerformed

    private void txt_cli_cpfFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txt_cli_cpfFocusLost

        //cria gerenciador do BancoImobiliaria
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("BancoImobiliaria");
        EntityManager em = emf.createEntityManager();

        //procura o cliente com o CPF digitado
        if (txt_cli_cpf.getText().length() == 0) return;
        
        Clientes cli = em.find(Clientes.class, txt_cli_cpf.getText());

        //se o Objeto cli existir, mostra seus dados
        if(cli != null) {
            txt_cli_nome.setText(cli.getNome());
            txt_cli_dtns.setText(String.valueOf(cli.getDtns()));
            txt_cli_tel.setText(cli.getTelefone());
            txt_cli_email.setText(cli.getEmail());
            txt_cli_end.setText(cli.getEndereco());

            //máscara para moeda em real
            Locale brasil = new Locale("pt","BR");
            DecimalFormatSymbols real = new DecimalFormatSymbols(brasil);
            DecimalFormat dinheiro_real = new DecimalFormat("###,###,##0.00",real);

            //mostra renda familiar e individual com a máscara da moeda real
            txt_cli_renda_familiar.setText(dinheiro_real.format(cli.getRendaFamiliar()));
            txt_cli_renda_individual.setText(dinheiro_real.format(cli.getRendaIndividual()));

            //seleciona o sexo do cliente
            if(cli.getSexo() == 'M')
                rad_cli_masc.setSelected(true);
            else if(cli.getSexo() == 'F')
                rad_cli_fem.setSelected(true);

            //encerra a trasação
            em.close();
            emf.close();
        }else {
            //limpa todos os campos exceto o CPF
            txt_cli_nome.setText("");
            txt_cli_dtns.setText("");
            txt_cli_tel.setText("");
            txt_cli_end.setText("");
            txt_cli_email.setText("");
            txt_cli_renda_individual.setText("");
            txt_cli_renda_familiar.setText("");
            rad_cli_masc.setSelected(false);
            rad_cli_fem.setSelected(false);
        }
}//GEN-LAST:event_txt_cli_cpfFocusLost

    private void txt_cli_cpfActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_cli_cpfActionPerformed

    }//GEN-LAST:event_txt_cli_cpfActionPerformed

    void limparCampos(){
        //limpa todos os campos do Formulario_cliente
        txt_cli_cpf.setText("");
        txt_cli_nome.setText("");
        txt_cli_dtns.setText("");
        txt_cli_tel.setText("");
        txt_cli_end.setText("");
        txt_cli_email.setText("");
        txt_cli_renda_individual.setText("");
        txt_cli_renda_familiar.setText("");
        rad_cli_masc.setSelected(false);
        rad_cli_fem.setSelected(false);

        //aponta cursor para o campo cpf
        //txt_cli_cpf.requestFocus();
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JToggleButton btn_cli_excluir;
    private javax.swing.JButton btn_cli_limpar;
    private javax.swing.JButton btn_cli_salvar;
    private javax.swing.JLabel lab_cli_cpf;
    private javax.swing.JLabel lab_cli_dtns;
    private javax.swing.JLabel lab_cli_email;
    private javax.swing.JLabel lab_cli_end;
    private javax.swing.JLabel lab_cli_nome;
    private javax.swing.JLabel lab_cli_renda_familiar;
    private javax.swing.JLabel lab_cli_renda_individual;
    private javax.swing.JLabel lab_cli_sexo;
    private javax.swing.JLabel lab_cli_tel;
    private javax.swing.ButtonGroup radGroup_cli_sexo;
    private javax.swing.JRadioButton rad_cli_fem;
    private javax.swing.JRadioButton rad_cli_masc;
    private javax.swing.JTextField txt_cli_cpf;
    private javax.swing.JTextField txt_cli_dtns;
    private javax.swing.JTextField txt_cli_email;
    private javax.swing.JTextField txt_cli_end;
    private javax.swing.JTextField txt_cli_nome;
    private javax.swing.JTextField txt_cli_renda_familiar;
    private javax.swing.JTextField txt_cli_renda_individual;
    private javax.swing.JTextField txt_cli_tel;
    // End of variables declaration//GEN-END:variables

}
